<template>
  <div class="ibk">
    <a-checkbox v-if="showAllCk" v-model="ckAll" @change="ckAllChange">全选</a-checkbox>
    <a-checkbox
      v-for="o in list"
      :key="`ck${o.key}`"
      v-model="o.ck"
      @change="ckChange">
      {{ o.name }}
    </a-checkbox>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'modelVal',
    event: 'change'
  },
  props: {
    modelVal: {
      type: String,
      default: ''
    },
    code: {
      type: String,
      default: '000'
    },
    showAllCk: {
      type: Boolean,
      default: true
    },
    options: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      val: [],
      list: [],
      ckAll: false
    }
  },
  mounted () {
    this.val = this.modelVal.split(',')
    this.search()
  },
  watch: {
    modelVal (v) {
      this.val = v.split(',')
    },
    val (v) {
      this.$emit('change', v.join(','))
    },
    code () {
      this.search()
    }
  },
  methods: {
    search () {
      if (this.options.length > 0) {
        this.list = this.options.map(t => {
          t.ck = this.val.includes(t.key)
          return t
        })
      } else {
        this.$http.get('/zg-system/dic/list', { code: this.code }, data => {
          this.list = data.map(t => {
            return {
              key: t.code,
              name: t.name,
              ck: this.val.includes(t.code)
            }
          })
        })
      }
    },
    ckAllChange (e) {
      this.list.forEach(t => {
        t.ck = e.target.checked
      })
      this.val = this.list.filter(t => {
        return t.ck
      }).map((t) => {
        return t.key
      })
    },
    ckChange () {
      this.ckAll = this.list.every(t => {
        return t.ck
      })
      this.val = this.list.filter(t => {
        return t.ck
      }).map((t) => {
        return t.key
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
